package com.example.maxmin;

import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;

class Point {
	public double x;
	public double y;
	public double z;
}

public class Main {
	static double maxMin(double[] path1, double[] path2) {
		var max = 0.0;
		for (int j = 0; j < path1.length; j += 3) {
			var jx = path1[j];
			var jy = path1[j + 1];
			var jz = path1[j + 2];
			var min = Double.MAX_VALUE;
			int i = 0;
			for (; i < path2.length - 9; i += 12) {
				var xd1 = path2[i] - jx;
				var yd1 = path2[i + 1] - jy;
				var zd1 = path2[i + 2] - jz;
				var xd2 = path2[i + 3] - jx;
				var yd2 = path2[i + 4] - jy;
				var zd2 = path2[i + 5] - jz;
				var xd3 = path2[i + 6] - jx;
				var yd3 = path2[i + 7] - jy;
				var zd3 = path2[i + 8] - jz;
				var xd4 = path2[i + 9] - jx;
				var yd4 = path2[i + 10] - jy;
				var zd4 = path2[i + 11] - jz;
				var dist1 = Math.sqrt(xd1 * xd1 + yd1 * yd1 + zd1 * zd1);
				var dist2 = Math.sqrt(xd2 * xd2 + yd2 * yd2 + zd2 * zd2);
				var dist3 = Math.sqrt(xd3 * xd3 + yd3 * yd3 + zd3 * zd3);
				var dist4 = Math.sqrt(xd4 * xd4 + yd4 * yd4 + zd4 * zd4);
				if (min > dist1)
					min = dist1;
				if (min > dist2)
					min = dist2;
				if (min > dist3)
					min = dist3;
				if (min > dist4)
					min = dist4;
			}
			for (; i < path2.length; i += 3) {
				var xd = path2[i] - jx;
				var yd = path2[i + 1] - jy;
				var zd = path2[i + 2] - jz;
				var dist = Math.sqrt(xd * xd + yd * yd + zd * zd);
				if (min > dist)
					min = dist;
			}
			if (max < min)
				max = min;
		}
		return max;
	}

	static double hausdorffDistance(double[] path1, double[] path2) {
		return Math.max(maxMin(path1, path2), maxMin(path2, path1));
	}

	static double[] pointList2Array(ArrayList<Point> pVec) {
		var a = new double[pVec.size() * 3];
		int i = 0;
		for (var p : pVec) {
			a[i++] = p.x;
			a[i++] = p.y;
			a[i++] = p.z;
		}
		return a;
	}

	public static void main(String[] args) throws Exception {
		var p1Json = Files.readString(Paths.get("../../path.json"));
		var p2Json = Files.readString(Paths.get("../../path1.json"));

		var listType = new TypeToken<ArrayList<Point>>() {
		}.getType();
		var p1Vec = pointList2Array(new Gson().fromJson(p1Json, listType));
		var p2Vec = pointList2Array(new Gson().fromJson(p2Json, listType));

		for (int i = 0; i < 3; i++)
			hausdorffDistance(p1Vec, p2Vec);

		var startTime = System.currentTimeMillis();
		var val = hausdorffDistance(p1Vec, p2Vec);
		System.out.printf("res is %f\n", val);
		System.out.printf("spend time is: %d ms\n", System.currentTimeMillis() - startTime);
	}
}
